import { Application, BackendSession } from "pinus"
import recordDao, { RecordDao } from "../dao/recordDao"


export default function (app: Application) {
    return new RecordService(app)
}

export class RecordService {
    private _recordDao: RecordDao

    public constructor(private app: Application) {
        this._recordDao = recordDao(app)
    }


    // 查询赢钱排行（前20）
    public async cashOutRank() {
        let recordList = await this._recordDao.cashOutRank()
        let userWinResult = recordList.results;
        if (userWinResult.length == 0) {
            return []
        }
        userWinResult.forEach(e => {
            e.username = e.username.replace(/(\w{1}).*(\w{1})/, "$1****$2")
        })
        return userWinResult;
    }

    //查询最近下注信息(前20条)
    public async cashOutMines() {
        let recordList = await this._recordDao.cashOutMines()
        let userWinResult = recordList.results;
        if (userWinResult.length == 0) {
            return []
        }
        userWinResult.forEach(e => {
            e.userName = e.userName.replace(/(\w{1}).*(\w{1})/, "$1****$2")
        })
        return userWinResult;
    }

    // 获取最大倍数记录（前20）
    public async multipleRank() {
        let recordList = await this._recordDao.multipleRank()
        let userMultResult = recordList.results;
        if (userMultResult.length == 0) {
            return []
        }
        userMultResult.forEach(e => {
            e.userName = e.userName.replace(/(\w{1}).*(\w{1})/, "$1****$2")
        })
        return userMultResult;
    }

    // 用户游戏记录(前20条)
    public async userRecord(uid: number) {
        let recordList = await this._recordDao.userRecord(uid)
        let userRecordResult = recordList.results;
        if (userRecordResult.length == 0) {
            return []
        }
        return userRecordResult;
    }

    // 游戏记录入库
    public async saveGameRecord(settlement: number, roundId: number, result: number, endType: number, operatorId: number) {
        let { results } = await this._recordDao.insertGameRecord(settlement, roundId, result, endType, operatorId)
        return results.affectedRows === 1
    }
    // 用户游戏记录入库
    public async saveBetRecord(betInfos: any[], userInfos: any[], roundId: number, robotBetInfos: any[]) {
        let values = []
        if (betInfos.length !== 0) {
            betInfos.forEach(e => {
                let userInfo = userInfos.find(u => u.userId === e.userId)
                let sqlParam = []
                let payOut = 0
                let multiple = 0
                let finishTime = new Date()
                let afterCoin = userInfo.coin
                if (e.cashOut) {
                    payOut = Math.floor(e.betCount * e.multiple / 100)
                    multiple = e.multiple
                    finishTime = e.finishTime
                    afterCoin = e.afterCoin
                }
                sqlParam.push(e.userId)
                sqlParam.push(userInfo.username)
                sqlParam.push(roundId)
                sqlParam.push(e.betCount)
                sqlParam.push(e.auto)
                sqlParam.push(multiple)
                sqlParam.push(payOut)
                sqlParam.push(e.betTime)
                sqlParam.push(finishTime)
                sqlParam.push(e.beforCoin)
                sqlParam.push(afterCoin)
                sqlParam.push(userInfo.expand)
                values.push(sqlParam)
            })
        }
        if (robotBetInfos.length !== 0) {
            robotBetInfos.forEach(e => {
                let sqlParam = []
                let payOut = 0
                let multiple = 0
                let finishTime = new Date()
                if (e.cashOut) {
                    payOut = Math.floor(e.betCount * e.multiple / 100)
                    multiple = e.multiple
                    finishTime = e.finishTime
                }
                sqlParam.push(e.userId)
                sqlParam.push(e.username)
                sqlParam.push(roundId)
                sqlParam.push(e.betCount)
                sqlParam.push(e.auto)
                sqlParam.push(multiple)
                sqlParam.push(payOut)
                sqlParam.push(e.betTime)
                sqlParam.push(finishTime)
                sqlParam.push(e.beforCoin)
                sqlParam.push(e.afterCoin)
                sqlParam.push('')
                values.push(sqlParam)
            })
        }

        const task = []
        let i = 1
        for (; i * 100 < values.length; i++) {
            task.push(this._recordDao.insertBetRecord(values.slice((i - 1) * 100, i * 100)))
        }
        task.push(this._recordDao.insertBetRecord(values.slice((i - 1) * 100, values.length)))
        if (task.length > 0) {
            await Promise.all(task)
        }
    }


    // 用户记录入库
    public async saveBetRecordMines(betInfos: any[], userInfos: any[], roundId: number,
        userId: number, sysMapDatas: any[], clickMapDatas: any[]) {

        let userInfo = userInfos.find(u => u.userId === userId)
        let betInfo = betInfos.find(u => u.userId === userId)
        let sysMapData = sysMapDatas.find(u => u.userId === userId)
        let clickMapData = clickMapDatas.find(u => u.userId === userId)

        let sqlParam = []
        let payOut = 0
        // let multiple = 0
        let finishTime = new Date()
        let afterCoin = userInfo.coin
        if (betInfo.cashOut) {
            payOut = Math.floor((betInfo.betCount * betInfo.multiple) - betInfo.betCount)
            // multiple = betInfo.multiple
            finishTime = betInfo.finishTime
            afterCoin = betInfo.afterCoin
        }
        sqlParam.push(betInfo.userId)
        sqlParam.push(userInfo.username)
        sqlParam.push(roundId)
        sqlParam.push(betInfo.betCount)
        sqlParam.push(betInfo.auto)
        sqlParam.push(betInfo.multiple)
        sqlParam.push(payOut)
        sqlParam.push(betInfo.betTime)
        sqlParam.push(finishTime)
        sqlParam.push(betInfo.beforCoin)
        sqlParam.push(afterCoin)
        sqlParam.push(userInfo.expand)
        this._recordDao.insertBetRecordMines(sqlParam)

        let sqlParam1 = []
        let diamondNum = 0
        if (betInfo.multiple > 0) {
            for (let i = 0; i < clickMapData.map.length; i++) {
                if (clickMapData.map[i] == 0) { diamondNum++ }
            }
        }

        sqlParam1.push(betInfo.userId)
        sqlParam1.push(roundId)
        sqlParam1.push(betInfo.multiple == 0 ? 0 : 1)
        sqlParam1.push(payOut)
        sqlParam1.push(sysMapData.map.toString())
        sqlParam1.push(clickMapData.map.toString())
        sqlParam1.push(betInfo.minesNum)
        sqlParam1.push(diamondNum)
        sqlParam1.push(finishTime)

        // 游戏记录入库
        this._recordDao.insertGameRecordMines(sqlParam1)
    }

    // 上一局游戏记录
    public async previousRecord() {
        let previousRecord = await this._recordDao.previousRecord()
        let previousRecordResult = previousRecord.results;
        if (previousRecordResult.length == 0) {
            return []
        }
        previousRecordResult.forEach(e => {
            e.username = e.username.replace(/(\w{1}).*(\w{1})/, "$1****$2")
        })
        return previousRecordResult;
    }
}
